namespace RBAC.Write.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.QualityCommand;

    /// <summary>
    /// 删除质量工单附件 处理器（软删除）
    /// </summary>
    public class QualityOrderAttachmentDeleteHandler : IRequestHandler<QualityOrderAttachmentDeleteCommand, APIResult<int>>
    {
        private readonly IBaseRepository<QualityOrderAttachment> _attRepo;
        private readonly ILogger<QualityOrderAttachmentDeleteHandler> _logger;

        public QualityOrderAttachmentDeleteHandler(IBaseRepository<QualityOrderAttachment> attRepo, ILogger<QualityOrderAttachmentDeleteHandler> logger)
        {
            _attRepo = attRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(QualityOrderAttachmentDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "Id无效", Data = 0 });

                var entity = _attRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (entity == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "附件不存在", Data = 0 });

                entity.IsDeleted = true;
                var rows = _attRepo.Update(entity);

                result.Code = rows > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = rows > 0 ? "删除附件成功" : "删除附件失败";
                result.Data = rows;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("删除质量工单附件被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "删除质量工单附件异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "删除质量工单附件异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
